package com.tressatisfiability.shared;

import java.io.Serializable;

public class Clausula implements Serializable {

	private static final long serialVersionUID = -1618307429251334076L;
	private int v1;
	private int v2;
	private int v3;
	private boolean b1;
	private boolean b2;
	private boolean b3;

	private boolean evaluation;

	private Clausula() {
		super();
	}

	public Clausula(int v1, int v2, int v3, boolean b1, boolean b2, boolean b3) {
		this.v1 = v1;
		this.v2 = v2;
		this.v3 = v3;
		this.b1 = b1;
		this.b2 = b2;
		this.b3 = b3;
		reEvaluate();
	}

	public boolean isSatisfied() {
		return evaluation;
	}

	public int[] getVariables() {
		int[] retorno = { v1, v2, v3 };
		return retorno;
	}

	private void reEvaluate() {
		boolean w1, w2, w3;

		if (v1 > 0) {
			w1 = b1;
		} else {
			w1 = !b1;
		}

		if (v2 > 0) {
			w2 = b2;
		} else {
			w2 = !b2;
		}

		if (v3 > 0) {
			w3 = b3;
		} else {
			w3 = !b3;
		}

		evaluation = w3 || w2 || w1;

	}

//	public void flipVariable(int v) {
//		if (Math.abs(v1) == v) {
//			if (b1) {
//				b1 = false;
//			} else {
//				b1 = true;
//			}
//		}
//		if (Math.abs(v2) == v) {
//			if (b2) {
//				b2 = false;
//			} else {
//				b2 = true;
//			}
//		}
//		if (Math.abs(v3) == v) {
//			if (b2) {
//				b2 = false;
//			} else {
//				b2 = true;
//			}
//		}
//		reEvaluate();
//	}

	public void flipVariable(int v) {
		if (Math.abs(v1) == v) {
			b1 = !b1;
		}
		if (Math.abs(v2) == v) {
			b2 = !b2;
		}
		if (Math.abs(v3) == v) {
			b3 = !b3;
		}
		reEvaluate();
	}

	public void setVariableValue(int v, boolean b) {
		if (Math.abs(v1) == v) {
			b1 = b;
		}
		if (Math.abs(v2) == v) {
			b2 = b;
		}
		if (Math.abs(v3) == v) {
			b3 = b;
		}
		reEvaluate();
	}

	@Override
	public String toString() {
		String s = "(";
		if (v1 < 0) {
			s += "~";
		}
		s += "x";
		s += Integer.toString(Math.abs(v1));
		s += " V ";

		if (v2 < 0) {
			s += "~";
		}
		s += "x";
		s += Integer.toString(Math.abs(v2));
		s += " V ";

		if (v3 < 0) {
			s += "~";
		}
		s += "x";
		s += Integer.toString(Math.abs(v3));
		s += ")";
		return s;
	}

	public String toHTML() {
		String s = "(";
		if (v1 < 0) {
			s += "~";
		}
		s += "x<sub>";
		s += Integer.toString(Math.abs(v1));
		s += "</sub>";
		s += " v ";

		if (v2 < 0) {
			s += "~";
		}
		s += "x<sub>";
		s += Integer.toString(Math.abs(v2));
		s += "</sub>";
		s += " v ";

		if (v3 < 0) {
			s += "~";
		}
		s += "x<sub>";
		s += Integer.toString(Math.abs(v3));
		s += "</sub>";
		s += ")";
		return s;
	}

}
